import MessageBoxComponent from "./MessageBox.vue";
import { App } from 'vue'


const MessageBox = (field): Promise<any> => {

    const messageBoxApp: App = createApp(MessageBoxComponent, { field: field });
    return new Promise((resolve, reject) => {
        showMessageBox(messageBoxApp, { resolve, reject })
    })
}

const showMessageBox = (app: App, { resolve, reject }) => {
    const oFragment = document.createDocumentFragment()
    const vm: any = app.mount(oFragment)
    document.body.appendChild(oFragment);
    vm.setVisible(true);

    watch(vm.state, state => {
        console.log(state);
        if (!state.visible) {
            switch (state.type) {
                case 'cancel':
                    reject()
                    break
                case 'confirm':
                    resolve(state.promptValue)
                    break
                default:
                    break
            }
            hideMessageBox(app);
        }
    })
}

const hideMessageBox = (app: App) => {
    app.unmount();
};

export { MessageBox }